#include"List.h"

LTNode* BuyListNode(LTDateType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("Malloc File");
		return NULL;
	}

	newnode->date = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

//void ListInit(LTNode* phead)
//{
//	LTNode* newnode = BuyListNode(-1);
//
//	phead = newnode;
//	phead->next = phead;
//	phead->prev = phead;
//
//}


LTNode* ListInit()
{
	LTNode* phead = BuyListNode(-1);

	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void ListDestroy(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}


bool ListEmpty(LTNode* phead)
{
	assert(phead);

	return phead->next == phead;
}


void ListPrint(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->date);
		cur = cur->next;
	}
	printf("\n");

}


void ListPushBack(LTNode* phead,LTDateType x)
{
	assert(phead);

	LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;

}


void ListPopBack(LTNode* phead)
{
	/*assert(phead);
	assert(!ListEmpty(phead));

	LTNode* tail = phead->prev;
	LTNode* tailPrev = tail->prev;

	tailPrev->next = phead;
	phead->prev = tailPrev;
	free(tail);
	tail = NULL;*/

	LTErase(phead->prev);
	
}

void ListPushFront(LTNode* phead, LTDateType x)
{
	assert(phead);

	LTNode* newnode = BuyListNode(x);
	LTNode* first = phead->next;

	first->prev = newnode;
	newnode->next = first;
	newnode->prev = phead;
	phead->next = newnode;

}

void ListPopFront(LTNode* phead)
{
	assert(phead);
	assert(!ListEmpty(phead));

	LTNode* first = phead->next;
	phead->next = first->next;
	first->next->prev = phead;
	free(first);
	first = NULL;

}

void LTInsert(LTNode* pos, LTDateType x)
{
	assert(pos);

	LTNode* newnode = BuyListNode(x);
	LTNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;

}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* prev = pos->prev->prev;
	LTNode* del = pos->prev;

	prev->next = pos;
	pos->prev = prev;
	free(del);
	del = NULL;

}